﻿using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Sustainalytics.Utils.WebApi.ErrorCodes;
using Sustainalytics.DataLayer.ConnectionStrings;
using Sustainalytics.Entities.ConnectionStrings;
using Sustainalytics.ClientDW.Entities;
using MongoDB.Driver;
using Sustainalytics.DataLayer;
using System.Configuration;
using System.Web.Http.Cors;

namespace Sustainalytics.Controversies.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    //[ClaimsChecker("api/v1/company/controversies")]
    [RoutePrefix("api/v1/company/{companyId}")]
    public class NewsArticlesController : ApiController
    {
        [Route("newsArticles")]
        public HttpResponseMessage Get(Guid companyId)
        {
            try
            {
                var collection = MongoDatabaseFactory.GetDatabase(GetConnectionString(ConnectionStringType.ClientDW))
                    .GetCollection<NewsArticle>();

                var newsArticles = collection.Find(x => x.CompanyId == companyId)
                    .Project(Builders<NewsArticle>.Projection.Include(x => x.PublicationDate)
                        .Include(x => x.Headline)
                        .Include(x => x.ExternalUrl)
                        .Include(x => x.Source))
                    .As<NewsArticle>()
                    .ToEnumerable()
                    .OrderByDescending(x => x.PublicationDate);

                return Request.CreateResponse(HttpStatusCode.OK, newsArticles);
            }
            catch (Exception)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError,
                    new { ErrorStatusCode = WebAPIGeneralErrorCodes.UnhandledException });
            }
        }

        public static string GetConnectionString(ConnectionStringType tip)
        {


            var connectionString = ConfigurationManager.ConnectionStrings["ClientPlatform"] == null
                ? "mongodb://localhost/ClientPlatform"
                : ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString ?? "mongodb://localhost/ClientPlatform";

            if (tip == ConnectionStringType.ClientPlatform)
            {
                return connectionString;
            }

            var connectionStringsManager =
                ConnectionStringsManager.GetInstance(ConnectionStringsRepository.GetInstance(connectionString));
            return connectionStringsManager.GetConnectionString(tip);
        }
    }
}
